// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;

namespace SnapObjects.Data
{
    internal class TableElement : SqlElement
    {
        public TableElement(string schema, string table, string alias)
            : base(String.IsNullOrWhiteSpace(alias) ? table : alias)
        {
            if (String.IsNullOrWhiteSpace(schema) && table.IndexOf('.') > 0)
            {
                var arr = table.Split('.');

                this.Table = arr[arr.Length - 1];
                this.Schema = arr[arr.Length - 2];
            }
            else
            {
                this.Table = table;
                this.Schema = schema;
            }

            this.Alias = alias;
            this.TableType = SqlTableType.TableName;
        }

        public TableElement(SqlBuildStatement statement, string alias) : this("", "", alias)
        {
            this.Statement = statement;
            this.TableType = SqlTableType.Statement;
        }

        public TableElement(string clause, string name) : base(name)
        {
            this.Table = clause;
            this.TableType = SqlTableType.Clause;
        }

        public override SqlElementType ElementType => SqlElementType.Table;

        public string Schema { get; protected set; }

        public string Table { get; protected set; }

        public string Alias { get; protected set; }

        public bool IsCross { get; internal set; }

        public SqlBuildStatement Statement { get; protected set; }

        public SqlTableType TableType { get; protected set; }

        public override SqlElement Clone()
        {
            return new TableElement(this.Table, this.ElementName)
            {
                Schema = this.Schema,
                Table = this.Table,
                Alias = this.Alias,
                IsCross = this.IsCross,
                TableType = this.TableType,
                Statement = this.Statement?.Clone()
            };
        }
    }
}
